package com.daervin.svc.parser.hot;

import com.daervin.svc.common.constants.Constants;
import com.daervin.svc.dal.model.HotItem;
import com.daervin.svc.parser.RootParser;
import org.apache.log4j.Logger;
import org.springframework.util.CollectionUtils;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.selector.Html;
import us.codecraft.webmagic.selector.Selectable;

import java.util.ArrayList;
import java.util.List;

import static com.daervin.svc.common.constants.HotSiteEnum.ZHIHU_DAILY;

/**
 * @author daervin
 * @version 1.0.0
 * @since 1.0.0
 */
public class ZhiHuDailyParser extends RootParser {
    private final static Logger LOGGER = Logger.getLogger(ZhiHuDailyParser.class);

    public ZhiHuDailyParser(String... parentUrls) {
        super(parentUrls);
    }

    @Override
    public Site getSite() {
        return super.getSite();
    }

    @Override
    public void listProcess(Page page) {
        Html html = page.getHtml();
        if (html == null) {
            return;
        }
        List<Selectable> newsViewList = html.xpath("//div[@class=\"main-content-wrap\"]//div[@class=\"row\"]//div[@class=\"col-lg-4\"]").nodes();
        if (CollectionUtils.isEmpty(newsViewList)) {
            return;
        }
        List<HotItem> hotItemList = new ArrayList<>();
        for (Selectable node : newsViewList) {
            try {
                List<Selectable> wrapNodes = node.xpath("div[@class=\"wrap\"]").nodes();
                if (CollectionUtils.isEmpty(wrapNodes)) {
                    continue;
                }
                for (Selectable item : wrapNodes) {
                    String title = item.xpath("//div[@class=\"box\"]//a//span[@class=\"title\"]/text()").get();
                    String links = item.xpath("//div[@class=\"box\"]//a").links().get();
                    long score = 0L;
                    hotItemList.add(new HotItem(ZHIHU_DAILY.ID, title, links, score));
                }
            } catch (Exception e) {
                System.err.println("ZhiHuDailyParser error: " + e.getMessage());
                LOGGER.error("ZhiHuDailyParser error", e);
            }
        }
        if (CollectionUtils.isEmpty(hotItemList)) {
            return;
        }
        page.putField(Constants.PARSER_RESULT, hotItemList);
    }

}
